from models.product import Product
from models import db


class ProductRepo:
    @staticmethod
    def find_by_paginated(page, pagesize):
        query = Product.query
        total_count = query.count()
        paginated_data = query.offset((page - 1) * pagesize).limit(pagesize).all()

        return {
            "data": paginated_data,
            "total": total_count,
        }

    @staticmethod
    def find_by_id(id):
        return Product.query.get(id)

    @staticmethod
    def insert(product_data):
        product = Product(**product_data)
        db.session.add(product)
        db.session.commit()
        return product

    @staticmethod
    def update(product, data):
        for key, value in data.items():
            setattr(product, key, value)
        db.session.commit()

    @staticmethod
    def delete_by_id(id):
        product = Product.query.get(id)
        if product:
            db.session.delete(product)
            db.session.commit()
            return True
        return False